//
//  YLJTools.m
//  ACE
//
//  Created by Mickey Yin on 2021/12/6.
//

#import "YLJTools.h"
#import <CommonCrypto/CommonDigest.h>

@implementation YLJTools


#pragma mark - 正则相关
- (BOOL)ht_isValidateByRegex:(NSString *)regex{
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:self];
}

//手机号有效性
- (BOOL)ht_isMobileNumber
{
    NSString *mobileRegex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}$";
    BOOL ret1 = [self ht_isValidateByRegex:mobileRegex];
    return ret1;
}

//邮箱
- (BOOL)ht_isEmail
{
    NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    return [self ht_isValidateByRegex:emailRegex];
}

//身份证号
- (BOOL)ht_simpleIDCard
{
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    return [self ht_isValidateByRegex:regex2];
}

//车牌
- (BOOL)ht_isCarNumber
{
    //车牌号:湘K-DE829 香港车牌号码:粤Z-J499港
    NSString *carRegex = @"^[\u4e00-\u9fff]{1}[a-zA-Z]{1}[-][a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fff]$";//其中\u4e00-\u9fa5表示unicode编码中汉字已编码部分，\u9fa5-\u9fff是保留部分，将来可能会添加
    return [self ht_isValidateByRegex:carRegex];
}
//Mac地址
- (BOOL)ht_isMacAddress
{
    NSString * macAddRegex = @"([A-Fa-f\\d]{2}:){5}[A-Fa-f\\d]{2}";
    return  [self ht_isValidateByRegex:macAddRegex];
}
//网址
- (BOOL)ht_isValidUrl
{
    NSString *regex = @"^((http)|(https))+:[^\\s]+\\.[^\\s]*$";
    return [self ht_isValidateByRegex:regex];
}
//中文
- (BOOL)ht_isValidChinese
{
    NSString *chineseRegex = @"^[\u4e00-\u9fa5]+$";
    return [self ht_isValidateByRegex:chineseRegex];
}
//邮编
- (BOOL)ht_isPostalcode
{
    NSString *postalRegex = @"^[0-8]\\d{5}(?!\\d)$";
    return [self ht_isValidateByRegex:postalRegex];
}
//工商税号
- (BOOL)ht_isTaxNo
{
    NSString *taxNoRegex = @"[0-9]\\d{13}([0-9]|X)$";
    return [self ht_isValidateByRegex:taxNoRegex];
}

#pragma 正则匹配URL
+ (BOOL)checkURL:(NSString*)url
{
    BOOL isMatch = [self regexMatch:@"^[0-9A-Za-z]{1,50}" target:url];
    return isMatch;
}

#pragma 正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard:(NSString*)idCard
{
    BOOL isMatch = [self regexMatch:@"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)" target:idCard];
    return isMatch;
}

#pragma 正则匹配手机号
+ (BOOL)checkTelNumber:(NSString*)telNumber
{
    BOOL isMatch = [self regexMatch:@"^1+[3578]+\\d{9}" target:telNumber];
    return isMatch;
}

#pragma 正则匹配用户密码 6-18位数字和字母组合
+ (BOOL)checkPassword:(NSString*)password
{
    BOOL isMatch = [self regexMatch:@"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}" target:password];
    return isMatch;
}

#pragma 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName:(NSString*)userName
{
    BOOL isMatch = [self regexMatch:@"^[a-zA-Z\u4E00-\u9FA5]{1,20}" target:userName];
    return isMatch;
}

+ (BOOL)regexMatch:(NSString *)regex target:(NSString *)target
{
    NSPredicate*pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    BOOL isMatch = [pred evaluateWithObject:target];
    return isMatch;
}

+ (NSString *)md5Str:(NSString *)md5str
{
    //传入参数,转化成char
    const char *cStr = [md5str UTF8String];
    //开辟一个16字节的空间
    unsigned char result[16];
    /*
     extern unsigned char * CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把str字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了md这个空间中
     */
    CC_MD5(cStr, (unsigned)strlen(cStr), result);
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ];
}

#pragma 将当前时间 UTCDate 转为时间戳
+ (NSString *)jxbTimeStampFromUTCDate:(NSDate *)UTCDate {
     
     NSTimeInterval timeInterval = [UTCDate timeIntervalSince1970]; // *1000,是精确到毫秒；这里是精确到秒;
     NSString *result = [NSString stringWithFormat:@"%.0f",timeInterval];
     
     return result;
}

#pragma 参数:时间戳
#pragma 返回值格式:2019-04-19 10:33:35.886
+ (NSString *)jxbUTCStringFromTimestamp:(NSString*)mStr {
    
    NSTimeInterval interval    = [mStr doubleValue]; // / 1000.0;
    NSDate *date              = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
    NSString *dateString      = [formatter stringFromDate: date];
    return dateString;
}

#pragma NSDate 转 字符串日期  年-月-日 时:分:秒
+ (NSString *)jxbUTCStringFromUTCDate:(NSDate *)UTCDate {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    //[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//直接指定时区，这里是东8区
    NSString *dateStr = [formatter stringFromDate:UTCDate];
    return dateStr;
}

#pragma 字典转json字符串方法
+ (NSString *)jxbConvertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        //NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return jsonString;
}

+ (void)setNSUserDefaults:(NSInteger)valueText key:(NSString *)keyText {
    // 官方规定类型使用
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    // 保存数据
    [userDefaults setInteger:valueText forKey:keyText];
    [userDefaults synchronize];
}

+ (NSUInteger)getNSUserDefaults:(NSString *)keyText {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSUInteger result = [userDefaults integerForKey:keyText];
    return result;
}

+ (NSString *)chineseCharacterCode:(NSString *)url {
    NSURL *originUrl = [NSURL URLWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSString *filePath = [originUrl absoluteString];
    return filePath;
}



+ (NSString *)dateToString:(NSDate *)timeDate {
    
    NSString *timeStr = [NSString stringWithFormat:@"%f", [timeDate timeIntervalSince1970]*1000];
    return timeStr;
}

// 字符串转时间戳 如：2017-4-10 17:15:10
+ (NSString *)getTimestampWithDate:(NSString *)timeStr {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // 设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:timeStr]; // 将字符串转换为时间对象
    NSString *tempStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000]; // 字符串转成时间戳,精确到毫秒*1000
    return tempStr;
}

#pragma mark --- 将时间转换成时间戳
+ (NSString *)getTimestampFromTime:(NSString *)startTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *datenow = [dateFormatter dateFromString:startTime];
    
//    NSTimeInterval timeSpem= [datenow timeIntervalSince1970];//date是要转化为秒数的那个日期
    // 时间转时间戳的方法:
    NSString *timeSpem = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    //NSLog(@"timeSp:-- %lld",timeSpem);//时间戳的值
    return timeSpem;
}

//参数:时间戳
//返回值格式:2019-04-19 10:33:35.886
+ (NSString *)jxbGetTimestamp:(NSString*)mStr{
    
    NSTimeInterval interval    =[mStr doubleValue]; // / 1000.0;
    NSDate *date              = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
    NSString *dateString      = [formatter stringFromDate: date];
    NSLog(@"时间戳对应的时间是:%@",dateString);
    return dateString;
}

//1.NSDate转NSString
+ (NSString *)jxbToosNSDateToNSString:(NSDate *)tempDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSString *timeStr = [formatter stringFromDate:tempDate];
    NSLog(@"NSDate转NSString--- %@  ---  %@", tempDate, timeStr);
    return timeStr;
}

//将当前时间（UTCDate）转为时间戳
+ (NSString *)jsbTimeStampFromUTCDate:(NSDate *)UTCDate {
    
    NSTimeInterval timeInterval = [UTCDate timeIntervalSince1970]; // *1000,是精确到毫秒；这里是精确到秒;
    NSString *result = [NSString stringWithFormat:@"%.0f",timeInterval];
    NSLog(@"1000,是精确到毫秒--- %@", result);
     
//     [self jxbLocalStringFromUTCString:result];
//     [self jxbGetTimestamp:result];
    return result;
}

+ (NSString *)textDateToDayStr {
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc]init];
    dateFmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *dateStr = [dateFmt stringFromDate:date];
    NSLog(@"方式二: %@",dateStr);
    return dateStr;
}

//iOS15.4 NSDateformatter 12小时制日期格式问题及解决
+ (NSDateFormatter *)DateFormatter {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.locale = [NSLocale systemLocale];
    dateFormatter.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return dateFormatter;
}

@end
